/*
 * @author: jackem.mojx@gmail.com
 */
package me.weijing.common;

import java.util.List;

import me.weijing.common.http.FileCacheStore;
import me.weijing.common.http.FileStore;
import me.weijing.common.http.NetBroadCastReceiver;
import me.weijing.common.http.NetBroadCastReceiver.NetworkStateListener;
import me.weijing.common.util.AZusIntentConstant;
import me.weijing.common.util.AZusPreferenceConst;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

public class ApplicationHelper implements NetworkStateListener {

    private static float density = 180;
    private static Context mContext;
    private static Handler mHandler;
    private static long mainUiThreadId;
    private static int width;
    private static int height;
    private static String strDeviceId;
    private static String strMarketType = "";
    private static String strLocalversion = "";
    private static String strServerversion;
    private static boolean backgroundStat = false;

    public static String getStrServerversion() {
        return strServerversion;
    }

    public static void setStrServerversion(String strServerversion) {
        ApplicationHelper.strServerversion = strServerversion;
    }

    private static int versionCode;
    private static String strUserAgent;
    private static boolean isHighDisplay = true;
    private static ApplicationHelper s_ins = null;
    private static int commType;

    private final static int ScreenType_480_850 = 0;
    private final static int ScreenType_480_800 = 1;
    private final static int ScreenType_455_320 = 2;
    private static NetBroadCastReceiver receiver = null;
    private static String downloadUrl;
    private static boolean shouldUpdate;
    private static String updateDesc;

    public static Context getContext() {
        return mContext;
    }

    public static Handler getMainHandler() {
        return mHandler;
    }

    public static long getMainUiThreadId() {
        return mainUiThreadId;
    }

    public static void setUserAgent(String userAgent) {
        strUserAgent = userAgent;
    }

    /*
     * public static String getUserAgent() { if
     * (TextUtils.isEmpty(strUserAgent)) { StringBuilder builder = new
     * StringBuilder();
     * builder.append("(hupan").append(strLocalversion).append(")(")
     * .append("Android;").append(Build.DEVICE).append(";")
     * .append(Build.VERSION.RELEASE).append(")(")
     * .append(getTTID()).append(")"); strUserAgent = builder.toString(); }
     * return strUserAgent; }
     */

    public static float getDensity() {
        return density;
    }

    public static int getScreenWidth() {
        return width;
    }

    public static int getScreenHeight() {
        return height;
    }

    public static int getScreenSizeType() {

        final int screenWidth = getScreenWidth();
        final int screenHeight = getScreenHeight();
        if (screenWidth >= 480 && screenHeight >= 850) {
            return ScreenType_480_850;
        }
        if (screenWidth == 480 && screenHeight == 800) {
            return ScreenType_480_800;
        }
        if (screenWidth <= 480 && screenHeight <= 320) {
            return ScreenType_455_320;
        }
        return ScreenType_480_850;
    }

    public static boolean isHighDisplay() {
        return isHighDisplay;
    }

    public static String getDeviceId() {
        if (TextUtils.isEmpty(strDeviceId)) {
            TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
            try {
                strDeviceId = tm.getDeviceId();
            } catch (Throwable e) {
                e.printStackTrace();
            }
            if (TextUtils.isEmpty(strDeviceId)) {
                SharedPreferences pref = mContext.getSharedPreferences(AZusPreferenceConst.AZUSPREF_FILENAME, Context.MODE_PRIVATE);
                strDeviceId = pref.getString(AZusPreferenceConst.AZUSPREF_KEY_APPDEVICEID, "");
                if (TextUtils.isEmpty(strDeviceId)) {
                    strDeviceId = java.util.UUID.randomUUID().toString();
                    SharedPreferences.Editor edit = pref.edit();
                    edit.putString(AZusPreferenceConst.AZUSPREF_KEY_APPDEVICEID, strDeviceId);
                    edit.commit();
                }
            }
        }
        return strDeviceId;
    }

    public static String getTTID() {/*
                                     * if (TextUtils.isEmpty(strMarketType) &&
                                     * mContext != null) { InputStream is =
                                     * null; BufferedReader br = null; try {
                                     * AssetManager am = mContext.getAssets();
                                     * is = am.open("ttid.dat"); br = new
                                     * BufferedReader(new
                                     * InputStreamReader(is)); strMarketType =
                                     * br.readLine().trim(); } catch (Throwable
                                     * e) { e.printStackTrace(); } finally { try
                                     * { if (br != null) br.close(); if (is !=
                                     * null) is.close(); } catch (Throwable e) {
                                     * e.printStackTrace(); } } } return
                                     * strMarketType;
                                     */
        return "1";
    }

    public static int dipToPx(float dipValue) {
        final float scale = getDensity();
        return (int) (dipValue * scale + 0.5f);
    }

    public static int pxToDip(float pxValue) {
        final float scale = getDensity();
        return (int) (pxValue / scale + 0.5f);
    }

    int commType() {
        return commType;
    }

    // initEnv is called within Application.onCreate
    ApplicationHelper() {

    }

    public static ApplicationHelper getInstance() {
        if (null == s_ins) {
            s_ins = new ApplicationHelper();
        }
        return s_ins;
    }

    public static void initEnv(Context context) {
        mContext = context;
        mHandler = new Handler(mContext.getMainLooper());
        mainUiThreadId = Thread.currentThread().getId();
        // ZusNotificationCenter.defaultCenter().init(mContext); //use
        // LocalBroadcastManager instead
        density = mContext.getResources().getDisplayMetrics().density;
        width = mContext.getResources().getDisplayMetrics().widthPixels;
        height = mContext.getResources().getDisplayMetrics().heightPixels;
        strDeviceId = getDeviceId();
        try {
            strLocalversion = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
            versionCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (NameNotFoundException e) {
            strLocalversion = "";
            e.printStackTrace();
        }
        // strUserAgent = getUserAgent();
        if (width >= 480 && height >= 800) {
            isHighDisplay = true;
        } else {
            isHighDisplay = false;
        }
        receiver = new NetBroadCastReceiver(ApplicationHelper.getInstance());
        commType = receiver.searchCommuType(mContext);

        /*
         * mContext.registerReceiver(receiver, new
         * IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
         */

        try {
            FileCacheStore.Init(context, FileCacheStore.DEFAULT_DATACACHE_CAPACITY, FileCacheStore.DEFAULT_SDCARDCACHE_CAPACITY);
        } catch (Throwable t) {
            t.printStackTrace();
        }
        try {
            FileStore.Init(context);
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

    public static void uninitEnv(Context context) {
        FileCacheStore.UnInit(context);
        /* mContext.unregisterReceiver(receiver); */
        receiver = null;
    }

    /**
     * Checks if the application is in the background (i.e behind another
     * application's Activity).
     * 
     * @param context
     * @return true if another application is above this one.
     */
    public static boolean isApplicationBroughtToBackground() {
        ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(mContext.getPackageName())) {
                return true;
            }
        }

        return false;
    }

    public static String getTopActivityName() {
        ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            return topActivity.getShortClassName();
        }
        return null;
    }

    public static void setBackgroundState(boolean btrue) {
        backgroundStat = btrue;
    }

    public static boolean getBackgroundState() {
        return backgroundStat;
    }

    @Override
    public void commuTypeChange(int type) {
        commType = type;
        Intent intent = new Intent(AZusIntentConstant.ACTION_NETWORK_CHANGE);
        intent.putExtra("nettype", commType);
        LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
    }

    public static String getStrDeviceId() {
        return strDeviceId;
    }

    public static void setStrDeviceId(String strDeviceId) {
        ApplicationHelper.strDeviceId = strDeviceId;
    }

    public static String getStrMarketType() {
        return strMarketType;
    }

    public static void setStrMarketType(String strMarketType) {
        ApplicationHelper.strMarketType = strMarketType;
    }

    public static String getStrLocalversion() {
        return strLocalversion;
    }

    public static void setStrLocalversion(String strLocalversion) {
        ApplicationHelper.strLocalversion = strLocalversion;
    }

    public static int getVersionCode() {
        return versionCode;
    }

    public static void setVersionCode(int versionCode) {
        ApplicationHelper.versionCode = versionCode;
    }

    public static String getStrUserAgent() {
        return strUserAgent;
    }

    public static void setStrUserAgent(String strUserAgent) {
        ApplicationHelper.strUserAgent = strUserAgent;
    }

    public static int getCommType() {
        return commType;
    }

    public static void setCommType(int commType) {
        ApplicationHelper.commType = commType;
    }

    public static String getDownloadUrl() {
        return downloadUrl;
    }

    public static void setDownloadUrl(String downloadUrl) {
        ApplicationHelper.downloadUrl = downloadUrl;
    }

    public static boolean isShouldUpdate() {
        return shouldUpdate;
    }

    public static void setShouldUpdate(boolean shouldUpdate) {
        ApplicationHelper.shouldUpdate = shouldUpdate;
    }

    public static String getUpdateDesc() {
        return updateDesc;
    }

    public static void setUpdateDesc(String updateDesc) {
        ApplicationHelper.updateDesc = updateDesc;
    }

}
